package com.fr.lintcode;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

/**
*作者：furong
*日期：2017年1月13日
*时间：下午4:35:43
*/
public class Q106 {
    /**
     * @param head: The first node of linked list.
     * @return: a tree node
     */
    public TreeNode sortedListToBST(ListNode head) {
    	List<Integer> list = new ArrayList<>();
    	while(head!= null){
    		list.add(head.val);
    		head= head.next;
    	}
    	int length = list.size();
    	return addTreeNode(null, list, 0, length -1);
    }

    private TreeNode addTreeNode(TreeNode node, List<Integer> list, int i, int j) {
    	if(i <= j){
    		int mid = (i + j) / 2;
    		if (node == null){
    			node = new TreeNode(list.get(mid));
    		}
    		node.left = addTreeNode(null, list, i, mid -1);
    		node.right = addTreeNode(null, list, mid+ 1, j);
    	}
		return node;
	}

	@Test
    public void testA() {
        ListNode head = new ListNode(1);
        ListNode l1 = new ListNode(2);
        ListNode l2 = new ListNode(3);
        ListNode l3 = new ListNode(4);
        ListNode l4 = new ListNode(5);
        ListNode l5 = new ListNode(6);
        ListNode l6 = new ListNode(7);
        ListNode l7 = new ListNode(8);
        ListNode l8 = new ListNode(9);
        head.next = l1;
        l1.next = l2;
        l2.next = l3;
        l3.next = l4;
        l4.next = l5;
        l5.next = l6;
        l6.next = l7;
        l7.next = l8;
        System.out.println(head);
        TreeNode rs = sortedListToBST(head);
        System.out.println(rs);
    }
}
